package com.base.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.sys.dto.SysRoleQueryDTO;
import com.base.sys.entity.SysRole;
import com.base.sys.service.ISysPermissionService;
import com.base.sys.service.ISysRoleService;
import com.base.util.Result;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gjj
 * @since 2018-11-27
 */
@RestController
@RequestMapping("/sys/sys-role")
public class SysRoleController {

    @Autowired
    private ISysRoleService sysRoleService;


    @RequestMapping("/list")
    @RequiresPermissions("role:query")
    public Result list(@RequestBody SysRoleQueryDTO sysRoleQueryDTO){
        Integer page = sysRoleQueryDTO.getPage();
        Integer limit = sysRoleQueryDTO.getLimit();
        QueryWrapper<SysRole> queryWrapper=new QueryWrapper<SysRole>();
        if(page==null&&limit==null){
            List<SysRole> list = sysRoleService.list(queryWrapper);
            return Result.successResult(list);
        }
        Page<SysRole> pageRequest=new Page<SysRole>(page,limit);
        if(!StringUtils.isEmpty(sysRoleQueryDTO.getRoleName())){
            queryWrapper.like("role.ROLE_NAME","%"+sysRoleQueryDTO.getRoleName()+"%");
        }
        IPage<SysRole> sysRoleIPage = sysRoleService.selectPageNew(pageRequest, queryWrapper);
        return Result.successResult(sysRoleIPage);
    }

    @RequestMapping("/save-or-update")
    @RequiresPermissions("role:edit")
    public Result saveOrUpdate(@RequestBody SysRole sysRole){
        String id = sysRole.getId();
        if(StringUtils.isEmpty(id)){
            sysRole.setVersion(1);
            sysRole.setCreateDate(new Date());
        }else{
            sysRole.setUpdateDate(new Date());
        }
        boolean b = sysRoleService.saveOrUpdate(sysRole);
        if(!b) {
            throw new RuntimeException();
        }
        return Result.successResult();
    }

    @RequestMapping("/delete")
    @RequiresPermissions("role:delete")
    public Result delete(@RequestBody List<SysRole> list){
        return sysRoleService.deleteBatch(list);
    }

    @RequestMapping("/assign-perm")
    @RequiresPermissions("role:assign")
    public Result assignPerm(@RequestBody SysRole role){
        return sysRoleService.assignPerm(role);
    }


}
